import {
  registerMicroApps,
  addGlobalUncaughtErrorHandler,
  start,
} from "qiankun";

export default async function () {
  const dataList = await fetch("/app.reg.json")
    .then((response) => response.json()) // 将响应解析为 JSON
    .catch((error) => console.error("Error: micro app load failed!")); // 处理错误
  const apps = dataList.filter((v) => v.container !== "iframe");
  registerMicroApps(apps, {
    beforeLoad(app) {
      console.log("before load", app.name);
      return Promise.resolve();
    },
    afterMount(app) {
      console.log("after mount", app.name);
      return Promise.resolve();
    },
  });

  /**
   * 添加全局的未捕获异常处理器
   */
  addGlobalUncaughtErrorHandler((event) => {
    console.error(event);
    const { message: msg } = event;
    // 加载失败时提示
    if (msg && msg.includes("died in status LOADING_SOURCE_CODE")) {
      message.error("微应用加载失败，请检查应用是否可运行");
    }
  });

  start({
    sandbox: {
      strictStyleIsolation: true, // 开启严格的样式隔离模式
      // experimentalStyleIsolation: true // 开启单实例场景子应用之间的样式隔离
    },
  });

  return dataList;
}
